//
//  PostImageCell.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/23.
//

import SwiftUI

/// 图片间距   私有全局变量
private let kImageSpace: CGFloat = 6.0

struct PostImageCell: View {
    
    let images: [String]
    let width: CGFloat
    
    var body: some View {
        
        Group {
                
            if images.count == 1 {
                
                PostImageCellRow(images: images, width: width*3/4)
                
            }
            else if images.count == 2 {
                
                PostImageCellRow(images: images, width: width)
            }
            else if images.count == 3 {
                PostImageCellRow(images: images, width: width)
            }
            else if images.count == 4 {
                VStack(spacing: kImageSpace) {
                    PostImageCell(images: Array(images[0...1]), width: width)
                    PostImageCell(images: Array(images[2...3]), width: width)
                }
            }
            else if images.count == 5 {
                VStack(spacing: kImageSpace) {
                    PostImageCell(images: Array(images[0...1]), width: width)
                    PostImageCell(images: Array(images[2...4]), width: width)
                }
            }
            else if images.count == 6 {
                VStack(spacing: kImageSpace) {
                    PostImageCell(images: Array(images[0...2]), width: width)
                    PostImageCell(images: Array(images[3...5]), width: width)
                }
            }
            
            
        }
        
        
    }
}

struct PostImageCellRow: View  {
    
    let images: [String]
    let width: CGFloat
    
    
    var body: some View {
        
        let pw = (self.width - kImageSpace * CGFloat(self.images.count - 1)) / CGFloat(self.images.count)
        
        HStack(spacing: kImageSpace) {
            ForEach(images, id:\.self) { image in
                
                loadImage(name: image)
                    .resizable()
                    .scaledToFill()
                    .frame(width: pw, height: pw)
                    .clipped()
            }
        }
    }
    
}

struct PostImageCell_Previews: PreviewProvider {
    static var previews: some View {
        
        let images = UserData().recomendPostList.list[0].images
        let width = ScreenWidth
        
        return Group {
            PostImageCell(images: Array(images[0...0]), width: width)
            PostImageCell(images: Array(images[0...1]), width: width)
            PostImageCell(images: Array(images[0...2]), width: width)
            PostImageCell(images: Array(images[0...3]), width: width)
            PostImageCell(images: Array(images[0...4]), width: width)
            PostImageCell(images: Array(images[0...5]), width: width)
        }
        // 设置自动预览的视图宽高
        .previewLayout(.fixed(width: width, height: 300))
    }
}
